package com.zhuhjay.framework.handler;

import com.zhuhjay.common.base.model.vo.HttpResult;
import com.zhuhjay.common.base.util.JacksonUtils;
import com.zhuhjay.common.web.annotation.NotHttpResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Nullable;

import static com.zhuhjay.common.base.constant.ApplicationConstant.BASE_PACKAGE;

/**
 * @author ZhuHJay
 * @date 2023/2/25 19:18
 */
@Slf4j
@ControllerAdvice(BASE_PACKAGE)
public class GlobalResponseBodyHandler implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType,
                            Class<? extends HttpMessageConverter<?>> converterType) {
        // 若返回值类型为 HttpResult 则不用做统一的拦截
        // 若方法上加了 @NotHttpResult 则该方法不用做统一的拦截
        return !returnType.getParameterType().equals(HttpResult.class) &&
                !returnType.hasMethodAnnotation(NotHttpResult.class);
    }

    @Override
    public Object beforeBodyWrite(@Nullable Object body, MethodParameter returnType,
                                  MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        // void 方法也会被拦截，此时 body 为 null
        // 如果是文件下载，则需要自行使用 void + @NotHttpResult

        // String 类型不能直接包装，需要进行特殊处理
        // 当返回值为 String 类型时，MediaType 为 text/plain;charset=UTF-8
        if (returnType.getParameterType().equals(String.class)){
            return JacksonUtils.writeValueAsString(HttpResult.ok(body));
        }
        return HttpResult.ok(body);
    }

}
